<script setup>
import { onMounted, reactive, ref } from "vue";
import TopButton from "@/components/Pengyq/TopButton.vue";
import { useRoute } from "vue-router";
import {debounce} from "@/utils/debounce"
import { showDialog } from 'vant';
import {
  issueShopCommodityAPI,
  shopCommodityImageUp,
} from "@/server/api/shopCommodity";
import router from "@/router";
import { ToastFun } from "@/hook/toast";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const route = useRoute();
let shopId = ref();
let swiperImg = ref([]); //图片展示

// 商品信息表单数据
let issueShopCommodityReq = ref({
  commodityImgList: [], //图片
  commodityName: "",
  commodityDetail: "",
  price: null,
  shopId: "",
  validityTime: null,
  residue: "",
  reservationInformation: "",
});

// 定义发布方法
const issueShopCommodityFun = async () => {
  issueShopCommodityReq.value.shopId = shopId.value;
  console.log(shopComImgListFiles.value,111);
  
    const uploadPromises = shopComImgListFiles.value.map(async (file) => {
    // 标记为正在上传状态
    file.status = 'uploading';
    file.message = '上传中...';

    const formData = new FormData();
    formData.append("file", file.file);
    try {
      const { data } = await shopCommodityImageUp(formData);
      if (data.code === 500) {
        // 上传失败，显示错误信息
        showDialog({
          title: '提示',
          message: `${data.msg}`,
        }).then(() => {});
        file.status = 'failed';
        file.message = '上传失败';
        swiperImg.value = swiperImg.value.filter(item => item !== file);
        return;
      }

      if (data.code === 200) {
        if (!Array.isArray( issueShopCommodityReq.value.commodityImgList)) {
          issueShopCommodityReq.value.commodityImgList = [];
        }

        const newImages = data.data;
        // 检查是否存在重复图片
        const uniqueImages = newImages.filter(img => 
          ! issueShopCommodityReq.value.commodityImgList.includes(img)
        );
        if (uniqueImages.length) {
          issueShopCommodityReq.value.commodityImgList.push(...uniqueImages);
          file.status = 'success';
          file.message = '上传成功';
          file.upPath=uniqueImages[0]
        } else {
          // 如果图片已存在
          showDialog({
            title: '提示',
            message: '图片已存在',
          }).then(() => {});
          file.status = 'failed';
          file.message = '图片已存在';
          swiperImg.value = swiperImg.value.filter(item => item !== file);
        }
      }
    } catch (error) {
      console.error("上传图片异常:", error);
      file.status = 'failed';
      file.message = '上传异常';
      swiperImg.value = swiperImg.value.filter(item => item !== file);
    }
  });
  try {
    await Promise.all(uploadPromises); // 等待所有上传请求完成
  } catch (error) {
    console.error("批量上传异常:", error);
  }
  ToastFun("Loading", { duration: 10000 });
  let { data } = await issueShopCommodityAPI(issueShopCommodityReq.value);
  if (data.code == 200) {
    ToastFun("", {});
    router.push("/ApplyStore");
  } else {
    ToastFun("", {});
  }
};

const debouncedIssueShopCommodityFun = debounce(issueShopCommodityFun, 1000);


const handlePublish = async (form) => {
  form.validate().then(() => {
    if (swiperImg.value.length === 0) {
      ToastFun("show", { msg: t("me.PersonalPosting.shop.imgTips5") });
      // ToastFun("show", { msg: t("me.PersonalPosting.uploadImage") });
      return; 
    }
   
    debouncedIssueShopCommodityFun();
  }).catch(() => {
    ToastFun("show", { msg: t('me.PersonalPosting.rules') });
    // ToastFun("show", { msg: t("me.PersonalPosting.fillAllFields") });
  });
};


//清空按钮
const goReturn = () => {
  issueShopCommodityReq.value.commodityName=""
  issueShopCommodityReq.value.commodityDetail=""
  issueShopCommodityReq.value.price=null
  issueShopCommodityReq.value.residue=""
  issueShopCommodityReq.value.reservationInformation=""
  issueShopCommodityReq.value.validityTime=null
 };

//发布按钮
/**
 * api接口方法
 */
// 商品图片的轮播上传


let shopComImgListFiles = ref([]);
  const shopComImgUpFun = async (files) => {
    if (!Array.isArray(files)) {
      files = [files]; 
      shopComImgListFiles.value.push(...files);  
    }
    else {
      shopComImgListFiles.value.push(...files);
    }
  };



// 图片上传大小限制方法
const onOversize = () => {
  ToastFun("show", {
    msg: t("upTip"),
  });
};
const fileDelete = (file, detail) => {
  // issueShopCommodityReq.value.commodityImgList=issueShopCommodityReq.value.commodityImgList.filter(item=> item !== file.upPath)
  shopComImgListFiles.value=shopComImgListFiles.value.filter(item=> item.objectUrl !== file.objectUrl)
};

const validateNonNegative = (field) => {
  if (issueShopCommodityReq.value[field] < 0) {
    issueShopCommodityReq.value[field] = 0; // 强制将负数改为0
    // ToastFun("show", { msg: "Please enter a positive number"}); // 提示用户
  }
};

const validatorNumber = (value) => {
    return value > 0
}

onMounted(() => {
  shopId.value = route.query.data;
});
</script>

<template>
  <!-- 顶部返回按钮 -->
  <TopButton :title="$t('me.PersonalPosting.item.title')" />

  <div class="Publish_item">
    <div class="text_main">
      <textarea cols="22" rows="6" disabled :placeholder="$t('me.PersonalPosting.shop.imgTips3')"
        style="background-color: #fff" />

      <div class="perSonal_content">
        <div class="file">
          <van-uploader :after-read="shopComImgUpFun" :max-size="5000 * 1024" @oversize="onOversize"
          @delete="fileDelete" preview-size="50rem" v-model="swiperImg"
           :max-count="8" multiple />
        </div>
      </div>
    </div>

   

    <van-form ref="form">
      <van-cell-group style="width: 370rem" inset>
        <van-field :label="$t('me.PersonalPosting.subTitle')" name="pattern" disabled />
        <van-field :placeholder="$t('me.PersonalPosting.item.tips3')" v-model.number="issueShopCommodityReq.price"
        :label="$t('me.PersonalPosting.price')" type="number" @input="validateNonNegative('price')"
         :rules="[{ required: true,validator : validatorNumber, message: $t('me.PersonalPosting.item.tips3') }]"  />
        <!-- 通过 pattern 进行正则校验 -->
     
        <!-- 通过 validator 进行函数校验 --> 

        <!-- 有效期 -->
        <van-field v-model.number="issueShopCommodityReq.validityTime" type="number" :label="$t('me.PersonalPosting.date')"
          name="validator" :placeholder="$t('me.PersonalPosting.dateTips')"  @input="validateNonNegative('validityTime')"
          :rules="[{ required: true,validator : validatorNumber, message: $t('me.PersonalPosting.rules') }]" />

        <!-- 商品详情 -->
        <van-field v-model="issueShopCommodityReq.commodityDetail" :label="$t('me.PersonalPosting.details')"
          name="validator"  :placeholder="$t('me.PersonalPosting.detailsTips')"
          :rules="[{ required: true, message: $t('me.PersonalPosting.rules') }]" />

        <!-- 库存 -->
        <van-field v-model.number="issueShopCommodityReq.residue" :label="$t('me.PersonalPosting.inventory')"
          name="validator" type="number" :placeholder="$t('me.PersonalPosting.inventoryTips')" @input="validateNonNegative('residue')"
          :rules="[{ required: true,validator : validatorNumber, message: $t('me.PersonalPosting.rules') }]" />

        <!-- 注意事项 -->
        <van-field name="validator" :label="$t('me.PersonalPosting.note')"
          v-model="issueShopCommodityReq.reservationInformation" :placeholder="$t('me.PersonalPosting.noteTips')"
          :rules="[{ required: true, message: $t('me.PersonalPosting.rules') }]" />

        <!-- 商品名 -->
        <van-field name="asyncValidator" :label="$t('me.PersonalPosting.itemName')"
          v-model="issueShopCommodityReq.commodityName" :placeholder="$t('me.PersonalPosting.itemNameTips')" :rules="[
            {
              required: true,
              message: $t('me.PersonalPosting.rules'),
            },
          ]" />
      </van-cell-group>

      <footer>
        <div class="footer_button">
          <button @click="goReturn">
            {{ $t("me.PersonalPosting.reset") }}
          </button>

          <button @click="handlePublish($refs.form)">
            {{ $t("me.PersonalPosting.confirm") }}
          </button>
        </div>
      </footer>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
.Publish_item {
  overflow: hidden;
  font-size: 14rem;
  background-color: #f5f5f5;
  padding: 80rem 10rem 0 10rem;
  width: 100%;
  box-sizing: border-box;
  min-height: 100vh;

  .text_main {
    position: relative;
    width: 100%;

    textarea {
      border-radius: 10rem;
      resize: none;
      padding: 10rem;
      border: 0;
      width: 100%;
      box-sizing: border-box;
      text-indent: 1em;
    }

    .perSonal_content {
      position: absolute;
      bottom: 10rem;
      left: 10rem;
      border-radius: 6rem;
      padding: 10rem 2rem 2rem 10rem;
      text-align: center;
      background-color: #e0e0e0;
      color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }

  .addressCoe {
    :deep(.van-cell-group--inset) {
      margin: 0;
      position: relative;
      margin-top: 10rem;
    }

    :deep(.van-button) {
      background-color: #642e8eff;
      color: #fff;
      border-radius: 10rem;
    }

    .van-popup--bottom {
      position: relative;
      overflow: auto;

      footer {
        position: relative;
        bottom: 0rem;
        left: 10rem;
        width: 90%;
        height: 50rem;
        display: flex;
        justify-content: center;
        color: #642e8eff;
        border: 2rem solid;
        border-radius: 10rem;
        font-size: 18rem;
        align-items: center;

        .icon {
          margin-right: 10rem;
          width: 25rem;
          height: 25rem;
          text-align: center;
          line-height: 25rem;
          border: 2rem solid;
          color: #642e8eff;
          border-radius: 50%;
          font-size: 20rem;
        }
      }
    }
  }

  .van-form {
    :deep(.van-cell__title) {
      min-width: 95rem;
    }

    .van-cell-group--inset {
      margin: 0;
      margin-top: 10rem;
    }
  }

  footer {
    width: 100%;
    position: absolute;
    bottom: -30rem;
    left: 0;

    .footer_button {
      width: 100%;
      display: flex;
      justify-content: space-around;
      padding-bottom: 16rem;
      position: fixed;
      bottom: 0;

      button {
        color: #fff;
        background-color: #642e8eff;
        width: 40%;
        height: 40rem;
        line-height: 40rem;
        border-radius: 20rem;
        text-align: center;
        border: 1rem solid;

        &:hover {
          color: #fff;
          background-color: #642e8eff;
        }
      }
    }
  }
}
</style>
 